#!/usr/bin/python

import heroes
import items
import abilities
import buffs
import dotaClasses
import inspect
import os

# Get the directory that this file is in


baseFilePath = os.path.dirname(os.path.realpath(__file__)) + "/"

# Constants for image paths 

abilityImagePrefix = "../web/icons/abilities/"
itemImagePrefix = "../web/icons/items/"
heroImagePrefix = "../web/icons/heroes/"


def fileToString(fileName):
	f = open(baseFilePath + fileName)
	return f.read()

def header():
	return fileToString("web/head") + "</div></body></html>"

#def workingDir():
#	return baseFilePath

# Get a list of heroes
heroList = []
for name, hero in inspect.getmembers(heroes):
	if inspect.isclass(hero):
		heroList.append(hero)

def listHeroes():
	outString = "Heroes found: "
	for hero in heroList:
		outString += hero.commonName + " "
	return outString

# Get a list of items

itemList = []
for name, item in inspect.getmembers(items):
	if inspect.isclass(item):
		itemList.append(item)

def listItems():
	outString = "Items found: "
	for item in itemList:
		outString += item.name + " "
	return outString

def handleError(errorID):
	return fileToString("web/head") + "An Error Occurred" + fileToString("web/foot")

def listElement(name, data):
	return "<div>" + name + ": " + str(data) + "</div>\n"

def listElementSingle(data):
	return "<div>" + str(data) + "</div>\n"

def test(req):
	return req.subprocess_env['QUERY_STRING']

def formRequestPart(field):
	return "&" + str(field.name) + "=" + str(field.value)

def fullRequest(form):
	outString = ""
	for field in form:
		outString += formRequestPart(field)
		
	outString = outString[1:]
	return outString
	
def stripRequest(form, string):
	outString = ""
	for field in form:
		if field.name != string:
			outString += formRequestPart(field)
		
	outString = outString[1:]
	return outString
	
		

def listCurrentItems(itemIDs, urlPrefix):
	outString = "<div class = \"currentItems\"><h2>Current Items</h2>"
	outString += listCurrentObjects("item", items.itemList, itemIDs, urlPrefix)
	outString += "</div>"	
	return outString

def listCurrentAbilities(abilIDs, urlPrefix):
	outString = "<div class = \"currentAbils\"><h2>Current Abilities</h2>"
	outString += listCurrentObjects("abil", abilities.abilList, abilIDs, urlPrefix)
	outString += "</div>"
	return outString
	
def listCurrentBuffs(buffIDs, urlPrefix):
	outString = "<div class = \"currentBuffs\"><h2>Current Buffs</h2>"
	outString += listCurrentObjects("buff", buffs.buffList, buffIDs, urlPrefix)
	outString += "</div>"
	return outString


def listCurrentObjects(objectType, objectList, objectIDs, urlPrefix):
	objectIDs.sort(key = lambda x: objectList[x.value.split('-')[0]].name)

	objectUrlParts = []
	outString = ""

	for i in range(len(objectIDs)):
		objectID = objectIDs[i].value
		objectUrlParts.append(formRequestPart(objectIDs[i]))


	for i in range(len(objectIDs)):
		objectID = objectIDs[i].value.split('-')[0]
		outString += "<div class = \"" + objectType + "Box\">"
		objectClass = objectList[objectID]
		objectName = objectClass.name
		outString += objectName
		if objectClass.maxLevel != 0:
			try:
				outString += " (Level " + objectIDs[i].value.split('-')[1] + ") "
			except:
				outString += " (Level 1) "
				
		tempUrlPart = ""
		for j in range(len(objectUrlParts)):
			if j != i:
				tempUrlPart += objectUrlParts[j]
			
		delUrl = urlPrefix + tempUrlPart

	

		if objectClass.maxLevel != 0:
			outString += " Level Up: "
			for l in range(1, objectClass.maxLevel + 1):
				levelUrlPart = delUrl + "&" + objectIDs[i].name + "=" + objectIDs[i].value.split('-')[0] + "-" + str(l)
				outString += " <a class=\"levelLink\" href = \""+levelUrlPart+"\">" + str(l) + "</a> "
		outString += " <a class=\"deleteLink\" href = \"" + delUrl + "\">Delete</a>"

		outString += "</div>\n"
	return outString
	
def printOptions(booleanOptions, choiceOptions, numericalOptions, urlPrefix):
	
	outString = ""
	outString += "<div id = \"options\">"
	outString += "<h2>Options</h2>"
	boolUrlParts = []
	choiceUrlParts = []
	numericalUrlParts = []

	# Boolean Options

	for option in booleanOptions:
		optionUrlPart = "&opt=" + option + "-" + str(booleanOptions[option].value)
		boolUrlParts.append(optionUrlPart)

	boolUrlPrefix = urlPrefix
	for i in choiceUrlParts + numericalUrlParts:
		boolUrlPrefix += i

	for option in booleanOptions:
		outString += "<div id = \"optionBox\">"
		outString += booleanOptions[option].displayName + ": "
		tempUrlPart = ""
		outString += str(booleanOptions[option].value) + " (" 
		for i in boolUrlParts:
			if not(i.split('=')[1].split('-')[0] == option):
				tempUrlPart += i
		optionUrlBase = boolUrlPrefix + tempUrlPart
		outString += "<a class=\"enable\" href = \"" + optionUrlBase + "&opt=" + option + "-True\">Enable</a> "
		outString += "<a class=\"disable\" href = \"" + optionUrlBase + "&opt=" + option + "-False\">Disable</a>"
		outString += ")</div>"


	# Numerical Options


	for option in numericalOptions:
		optionUrlPart = "&opt=" + option + "-" + str(numericalOptions[option].value)
		numericalUrlParts.append(optionUrlPart)

	numericalUrlPrefix = urlPrefix

	for i in choiceUrlParts + boolUrlParts:
		numericalUrlPrefix += i

	for option in numericalOptions:
		outString += "<div id = \"optionBox\">"
		outString += numericalOptions[option].displayName + ": "
		tempUrlPart = ""
		outString += str(numericalOptions[option].value) + " (" 
		for i in numericalUrlParts:
			if not(i.split('=')[1].split('-')[0] == option):
				tempUrlPart += i
		optionUrlBase = numericalUrlPrefix + tempUrlPart
		#outString += "<a href = \"" + optionUrlBase + "&opt=" + option + "-True\">Enable</a> "
		#outString += "<a href = \"" + optionUrlBase + "&opt=" + option + "-False\">Disable</a>"
		outString += ")</div>"



	# Choice options

	for option in choiceOptions:
		optionUrlPart = "&opt=" + option + "-" + str(choiceOptions[option].value)
		choiceUrlParts.append(optionUrlPart)

	choiceUrlPrefix = urlPrefix

	for i in choiceUrlParts + boolUrlParts:
		choiceUrlPrefix += i

	for option in choiceOptions:
		outString += "<div id = \"optionBox\">"
		optionObj = choiceOptions[option]
		outString += optionObj.displayName + ": "
		tempUrlPart = ""
		outString += str(optionObj.displayValues[optionObj.value]) + " (" 
		for i in choiceUrlParts:
			if not(i.split('=')[1].split('-')[0] == option):
				tempUrlPart += i
		optionUrlBase = choiceUrlPrefix + tempUrlPart
		for j in range(len(optionObj.displayValues)):
			
			outString += "<a class=\"optionButton\" href = \"" + optionUrlBase + "&opt=" + option + "-" + str(j) + "\">" + optionObj.displayValues[j] + "</a> "
		outString = outString[:-1]
		outString += ")</div>"

 
	#outString += str(boolUrlParts)




	outString += "</div>"
	return outString

def buildHero(req):
	
	urlPrefix = "buildHero?"

	#try:
	h = heroes.heroDict[req.form.getfirst('hero', 'invalid')]()
	
	
	#except:
	#	return handleError(0)
	#return str(h.inventory)
	h.level = int(req.form.getfirst('level', 1))


	outString = ""

	itemIDs = req.form.getlist('item')
	for itemID in itemIDs:
		itemArray = itemID.value.split('-')
		if len(itemArray) == 2:
			item = items.itemList[itemArray[0]](int(itemArray[1]))
		else:
			item = items.itemList[itemArray[0]]()
		outString += str(item)
		h.addItem(item)


	abilIDs = req.form.getlist('abil')
	for abilID in abilIDs:
		abilArray = abilID.value.split('-')
		if len(abilArray) == 2:
			abil = abilities.abilList[abilArray[0]](int(abilArray[1]))
		else:
			abil = abilities.abilList[abilArray[0]]()
		outString += str(abil)
		h.addAbility(abil)

	buffIDs = req.form.getlist('buff')
	for buffID in buffIDs:
		buffArray = buffID.value.split('-')
		if len(buffArray) == 2:
			buff = buffs.buffList[buffArray[0]](int(buffArray[1]))
		else:
			buff = buffs.buffList[buffArray[0]]()
		outString += str(buff)
		h.addBuff(buff)
		
		
	# Options

	booleanOptions = {}
	choiceOptions = {}
	numericalOptions = {}

	optionValues = {}
	for optionField in req.form.getlist('opt'):
		name = optionField.value.split('-')[0]
		value = optionField.value.split('-')[1]
		if value == "True":
			value = True
		elif value == "False":
			value = False
		else:
			value = float(value)
		optionValues[name] = value

	classes = []
	for modifierID in itemIDs+abilIDs+buffIDs:
		if modifierID.name == "item":
			modifier = items.itemList[modifierID.value.split('-')[0]]
		if modifierID.name == "abil":
			modifier = abilities.abilList[modifierID.value.split('-')[0]]
		if modifierID.name == "buff":
			modifier = buffs.buffList[modifierID.value.split('-')[0]]

		for optionName, option in modifier.options.items():
			classes.append(str(option.__class__))
			if option.__class__ == dotaClasses.booleanOption:
				booleanOptions[optionName] = option
				try:
					if str(optionValues[optionName])=="True":
						option.value = True
					else: 
						option.value = False
				except: # If a value isn't specified, use default
					pass

			if option.__class__ == dotaClasses.choiceOption:
				choiceOptions[optionName] = option
				try:
					option.value = int(optionValues[optionName])
				except:
					pass

			if option.__class__ == dotaClasses.numericalOption:
				numericalOptions[optionName] = option
				try:
					option.value = float(optionValues[optionName])
				except:
					pass

	

	outString = fileToString("web/head")
	
	
	
	outString += "<div id = \"hero\">\n<div id = \"heroStats\">\n<h2>Hero Statistics</h2>\n<div class = \"attributeList\">"
	outString += listElement("Hero Name", h.commonName)
	outString += listElement("Hero Level", h.level)
	outString += listElement("Strength", str(h.getTotalStr()) + " (" + (str(h.getBaseStr()) + " + " + str(h.getBonusStr())) + ")")
	outString += listElement("Agility", str(h.getTotalAgi()) + " (" + (str(h.getBaseAgi()) + " + " + str(h.getBonusAgi())) + ")")
	outString += listElement("Intelligence", str(h.getTotalInt()) + " (" + (str(h.getBaseInt()) + " + " + str(h.getBonusInt())) + ")")
	outString += listElement("Damage", str(h.getTotalDamage()) + " (" + str(h.getMinBaseDamage()) + "-" + str(h.getMaxBaseDamage()) + " +" + str(h.getBonusDamage()) + ")")
	outString += listElement("Attack Speed", str(h.getTotalIAS()) + " (" + str(h.getAttacksPerSecond()) + " Attacks Per Second)")
	outString += listElement("HP", str(h.getTotalHP()) + " (" + str(h.getTotalHPR()) + " Regen Per Second)")
	outString += listElement("Mana", str(h.getTotalMP()) + " (" + str(h.getTotalMPR()) + " Regen Per Second)")
	outString += listElement("Armor", str(h.getTotalArmor()) + " (" + str(h.getBaseArmor()) + " + " + str(h.getBonusArmor()) + ")")
	outString += listElement("Spell Resistance", h.getSpellResistance())
	
	outString += "</div>\n</div>"


	# List current items with a delete button next to each

	outString += listCurrentItems(itemIDs, urlPrefix + stripRequest(req.form.list, "item"))

	outString += listCurrentAbilities(abilIDs, urlPrefix + stripRequest(req.form.list, "abil"))

	outString += listCurrentBuffs(buffIDs, urlPrefix + stripRequest(req.form.list, "buff"))

	


		#if modifierID.name = "buff":
		#	modifier = items.itemList[modifierID.value]

	outString += printOptions(booleanOptions, choiceOptions, numericalOptions, urlPrefix + stripRequest(req.form.list, "opt"))



	outString += "</div>"

	# Stuff on the right

	outString += "<div id = \"objectPicker\">\n"

	# Ability picker

	outString += "<div id = \"abilityPicker\">\n"

	for ability in h.heroAbilities:
		abilityAddUrl = ""
		for item in abilities.abilList:
			if abilities.abilList[item] == ability:
				abilityAddUrl = item
		outString += "<a href = \"" + urlPrefix + fullRequest(req.form.list) + "&abil=" + abilityAddUrl + "\"><div class = \"newHeroAbility\">\n"
		if ability.image != None:

			outString += "<img class = \"abilityPic\" src = \"" + abilityImagePrefix + ability.image + "\">"
		else:
			outString += ability.name
		outString += "</a></div>"
	

	outString += "</div>" # Closing abilityPicker

	# Item picker
	outString += "<div id = \"itemPicker\">\n"

	for itemShop in items.itemShopList:
		outString += "<div class = \"itemShop\"><h3>" + itemShop.name + "</h3>"
		count = 0
		for item in itemShop.items:
			if count == 4:
				outString += "<br>"
				count = 0
			count += 1
			itemObject = items.itemList[item]() # have to instantiate 
								# due to properties
			outString += "<a href = \"" + urlPrefix + fullRequest(req.form.list) + "&item=" + item + "\"><div class = \"newItem\">\n"
			if itemObject.image != None:

				outString += "<img class = \"itemPic\" src = \"" + itemImagePrefix + itemObject.image + "\">"
			else:
				outString += itemObject.name
			outString += "</a></div>"
		outString += "</div>" # Closing itemShop

	outString += "</div>" # Closing itemPicker
	outString += "<div class = \"clearDummy\"></div>"

	outString += "</div>" # Closing objectPicker
	outString += "<div class = \"clearDummy\"></div>"



	# Print out footer
	outString += fileToString("web/foot")


	
	return outString

